import re
import json
import requests

# 读取文本文件
def read_file(file_path):
    with open(file_path, 'r', encoding='utf-8') as file:
        content = file.read()
    
    # 使用正则表达式分割JSON对象
    pattern = re.compile(r'\{.*?\}', re.DOTALL)
    matches = pattern.findall(content)
    
    # 解析每个JSON对象
    images = []
    for match in matches:
        try:
            # 解析JSON对象
            parsed = json.loads(match)
            images.append(parsed)
        except json.JSONDecodeError as e:
            print(f"解析错误: {e}")
            print(f"有问题的字符串: {match}")
    
    return images

# 下载图片函数
def download_image(url, name):
    response = requests.get(url)
    if response.status_code == 200:
        with open(name + ".png", 'wb') as f:
            f.write(response.content)
        print(f"成功下载 {name}")
    else:
        print(f"下载失败 {name}")

# 主函数
def main():
    # 读取图片信息
    images = read_file('image_links.txt')
    
    # 遍历图片列表，调用下载函数
    for image in images:
        download_image(image['img'], image['name'])

    print("所有图片下载完成！")

if __name__ == "__main__":
    main()